<?php

namespace app\wechat\controller;

use app\admin\model\Authorizer;
use app\admin\model\ReplyMessage;
use app\admin\model\SubscribeMsgAcc;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use EasyWeChat\Kernel\Messages\Raw;
use EasyWeChat\Kernel\Messages\Text;
use think\cache\driver\Redis;

/**
 * @author zero
 * @Time 2018/12/17
 *
 * Class Msg
 * @package app\wechat\controller
 *
 * 公众号回调
 */
class Msg extends Platform
{

    public $platform; // easywechat第三方实例
    public $return_message; // 回复消息

    public function __construct()
    {
        parent::__construct();
        // 获取第三方平台
        $this->platform = $this->getPlatform();
    }

    // 公众号回调
    public function callback($appid)
    {
        $ser = $this->platform->server; // 获取第三方平台server
        $msg = $ser->getMessage(); // 获取传入的msg

        if ($msg) {
            $openid = $msg['FromUserName']; // 获取用户信息
            $msgType = $msg['MsgType']; // 消息类型

            if ($msgType == 'event') {
                $event = $msg['Event'];
                if ($event == 'TEMPLATESENDJOBFINISH') {
                    return;
                } else if ($event == 'SCAN' || $event == 'CLICK' || $event == 'VIEW' || $event == 'scancode_push' || $event == 'scancode_waitmsg') {
                    $this->save_openid($appid, $openid);
                } else if ($event == 'subscribe') {
                    $this->save_openid($appid, $openid);
                    // 关注后回复
                    $this->handler_subscribe($appid, $openid);
                }
            } else if ($msgType == 'image' || $msgType == 'voice' || $msgType == 'video' || $msgType == 'location' || $msgType == 'shortvideo' || $msgType == 'link') {
                $this->save_openid($appid, $openid);
            } else if ($msgType == 'text') {
                $this->save_openid($appid, $openid);
                if ($msg['Content'] == 'openid') {
                    $this->return_openid($appid);
                }
            }
        }
    }

    // 保存openid
    public function save_openid($appid, $openid)
    {
        $openid_redis = new Openid();
        $openid_redis->add_openid($appid, $openid);
    }

    // 处理openid回复
    public function return_openid($appid)
    {
        $msg = new Text();
        $gh = $this->getGh($appid);
        $gh->server->push(function ($msg) {
            return $msg['FromUserName'];
        });
//        $gh->template_message
        $gh->server->serve()->send();
    }

    // // 处理小程序卡片
    // public function return_xcx($appid, $openid)
    // {
    //     $gh = $this->getGh($appid);
    //     $message = new Raw('{
    //         "touser":"'. $openid . '",
    //         "msgtype":"miniprogrampage",
    //         "miniprogrampage":
    //         {
    //              "title": "小程序测试",
    //              "appid": "wxe42ac5dd0f116b26",
    //              "pagepath": "",
    //              "thumb_media_id": "http://feeder-nx.oss-cn-shanghai.aliyuncs.com/img/e5a68df4ce50fd35a710ee5abc5eb8c1.png"
    //         }
    //     }');
    //     $gh->customer_service->message($message)->to($openid)->send();
    // }

    // 处理订阅回复信息
    public function handler_subscribe($appid)
    {
        $acc = Authorizer::get(['appid' => $appid]);
        if ($acc) {
            $msgid = SubscribeMsgAcc::where('ghid', $acc->ghid)->value('msgid');
            if ($msgid) {
                // 获取该账号绑定的关注回复消息
                $reply_msg = ReplyMessage::where('is_subscribe', 1)->where('id', $msgid)->find();
                if ($reply_msg) {
                    // 根据消息类型处理
                    if ($reply_msg->type == 'text') {
                        $this->return_message = $this->get_content($msgid);
                    } else if ($reply_msg->type == 'news') {
                        $content = json_decode($this->get_content($msgid), true);
                        $this->return_message = $this->handler_news($content);
                    }
                    // 通过普通回复,回复消息
                    $gh = $this->getGhWithToken($appid, $acc->refresh_token);
                    $gh->server->push(function ($msg) {
                        return $this->return_message;
                    });
                    $gh->server->serve()->send();
                }
            }
        }
    }

    // 处理图文信息拼接
    public function handler_news($items)
    {
        $news = array();
        foreach ($items as $item) {
            $newsItem = new NewsItem([
                'title' => $item['title'],
                'description' => $item['desc'],
                'url' => $item['url'],
                'image' => $item['img_url'],
            ]);
            array_push($news, $newsItem);
        }
        return new News($news);
    }

    // 在redis中获取消息content
    public function get_content($msgid)
    {
        $redis = new Redis();
        return $redis->get($msgid . '_reply_msg');
    }

}
